package com.ganmiao.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.Map.Entry;

/**
 * @Author zero.yin
 * @Date 2022/8/4 20:38
 * @Desc
 */
public class SortUtils {

    /**
     * @param paramMap 参数
     * @return
     */
    public static String paramsKeySort(Map<String, Object> paramMap) {
        String formatParams = "";
        try {
            List<Entry<String, Object>> itmes = new ArrayList<Entry<String, Object>>(paramMap.entrySet());
            //对所有传入的参数按照字段名从小到大排序
            //Collections.sort(items); 默认正序
            //可通过实现Comparator接口的compare方法来完成自定义排序
            Collections.sort(itmes, new Comparator<Entry<String, Object>>() {
                @Override
                public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
                    // TODO Auto-generated method stub
                    return (o1.getKey().toString().compareTo(o2.getKey()));
                }
            });

            //构造URL键值对的形式
            StringBuffer sb = new StringBuffer();
            for (Entry<String, Object> item : itmes) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    Object val = item.getValue();
                    sb.append(key + "=" + val);
                    sb.append("&");
                }
            }

            formatParams = sb.toString();
            if (StringUtils.isNotBlank(formatParams)) {
                formatParams = formatParams.substring(0, formatParams.length() - 1);
            }
        } catch (Exception e) {
            return "";
        }

        return formatParams;
    }
}
